package com.sunchp.nio.sample.thrift;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.SocketException;
import java.nio.channels.*;

public class NonblockingServerTransport implements ServerTransport {
    private static final Logger LOGGER = LoggerFactory.getLogger(NonblockingServerTransport.class);

    private ServerSocketChannel serverSocketChannel = null;
    private ServerSocket serverSocket = null;

    public NonblockingServerTransport(InetSocketAddress bindAddr, int backlog) {
        try {
            serverSocketChannel = ServerSocketChannel.open();
            serverSocketChannel.configureBlocking(false);
            // Make server socket
            serverSocket = serverSocketChannel.socket();
            // Prevent 2MSL delay problem on server restarts
            serverSocket.setReuseAddress(true);
            // Bind to listening port
            serverSocket.bind(bindAddr, backlog);
        } catch (IOException ioe) {
            serverSocket = null;
            throw new TransportException("Could not create ServerSocket on address " + bindAddr.toString() + ".", ioe);
        }
    }

    public void registerSelector(Selector selector) {
        try {
            // Register the server socket channel, indicating an interest in
            // accepting new connections
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        } catch (ClosedChannelException e) {
            // this shouldn't happen, ideally...
            // TODO: decide what to do with this.
        }
    }

    @Override
    public void listen() throws TransportException {
        // Make sure not to block on accept
        if (serverSocket != null) {
            try {
                serverSocket.setSoTimeout(0);
            } catch (SocketException sx) {
                sx.printStackTrace();
            }
        }
    }

    public final Transport accept() throws TransportException {
        Transport transport = acceptImpl();
        if (transport == null) {
            throw new TransportException("accept() may not return NULL");
        }
        return transport;
    }

    protected Transport acceptImpl() throws TransportException {
        if (serverSocket == null) {
            throw new TransportException(TransportException.NOT_OPEN, "No underlying server socket.");
        }
        try {
            SocketChannel socketChannel = serverSocketChannel.accept();
            if (socketChannel == null) {
                return null;
            }
            NonblockingTransport tsocket = new NonblockingTransport(socketChannel);
            return tsocket;
        } catch (IOException iox) {
            throw new TransportException(iox);
        }
    }

    @Override
    public void interrupt() {
        // The thread-safeness of this is dubious, but Java documentation suggests
        // that it is safe to do this from a different thread context
        close();
    }

    @Override
    public void close() {
        if (serverSocket != null) {
            try {
                serverSocket.close();
            } catch (IOException iox) {
                LOGGER.warn("WARNING: Could not close server socket: " + iox.getMessage());
            }
            serverSocket = null;
        }
    }

    public int getPort() {
        if (serverSocket == null)
            return -1;
        return serverSocket.getLocalPort();
    }
}
